package com.xinghou.platform.dao.mange.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.xinghou.platform.dao.mange.MessageDAO;
import com.xinghou.platform.dao.mange.UserInfoDAO;
import com.xinghou.platform.dao.mange.VestAssignedDAO;
import com.xinghou.platform.dao.mange.VestDAO;
import com.xinghou.platform.dao.mange.service.LoadResourceService;
import com.xinghou.platform.model.main.Message;
import com.xinghou.platform.model.main.Vest;
import com.xinghou.platform.model.main.VestAssigned;

@Service
public class LoadResourceServiceImpl implements LoadResourceService {
	//初步设定每位运营处理10个对话
	public static final int COUNT = 10;
	public static final int STATUS = 0;
	// 所有未处理机器人信息
	public static List<Message> messagelist = new ArrayList<Message>();
	// 所有运营人员
	public static List<Vest> vestlist = new ArrayList<Vest>();
	@Resource
	private MessageDAO messageDAO;
	@Resource
	private VestDAO vestDAO;
	@Resource
	private VestAssignedDAO vestAssignedDAO;
	@Resource
	private UserInfoDAO userInfoDAO;

	public void start() {	
		messagelist = messageDAO.getMsg(Short.valueOf(STATUS+""));
		vestlist = vestDAO.getAllVests();
		int count = vestAssignedDAO.getvestAssignedCount(-1);
		if(count<vestlist.size()*COUNT)
		{
			//得到所有运营人员进行任务分配
			int index=1;
			OK:
			for(int i=0;i<COUNT;i++){
				for(Vest vest : vestlist)
				{
					if(index>messagelist.size())
					{
						break OK;
					}
					//查询某位运营当前正在处理用户数量
					int vcount = vestAssignedDAO.getvestAssignedCount(vest.getVestId());
					if(vcount>=COUNT)
					{
						continue;
					}
					VestAssigned vestAssigned = new VestAssigned();
					int vestId = vest.getVestId();
					Message message = messagelist.get(index - 1);
					int trueid = message.getSenderId();
					int fakeid = message.getReceiverId();
					// 防止一个用户给另一个用户连续发了多条消息
					VestAssigned va = vestAssignedDAO.isOrNotVestAssigned(trueid,fakeid, STATUS);
					while (va != null) {
						index++;
						if(index>messagelist.size())
						{
							break OK;
						}
						message = messagelist.get(index - 1);
						trueid = message.getSenderId();
						fakeid = message.getReceiverId();
						va = vestAssignedDAO.isOrNotVestAssigned(trueid, fakeid,STATUS);
					}
					vestAssigned.setVestId(vestId);
					vestAssigned.setFakeId(message.getReceiverId());
					vestAssigned.setFakeName(userInfoDAO.getUserInfoById(fakeid).getNickName());
					vestAssigned.setTrueId(message.getSenderId());
					vestAssigned.setTrueName(userInfoDAO.getUserInfoById(trueid).getNickName());
					vestAssigned.setTest(message.getText());
					vestAssigned.setStatus(STATUS);
					vestAssigned.setMsgId(message.getMsgId());
					vestAssignedDAO.saveVestAssigned(vestAssigned);
					index++;
				}
			}
			System.out.println("静态块加载完成，初步任务已分配");
		}

	}

}
